package org.jiuling.weather.moji.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.jiuling.local.tools.convert.DateConvert;
import org.jiuling.local.tools.enums.DateTimeFormatEnum;
import org.jiuling.local.tools.exception.LocalToolsException;
import org.jiuling.local.tools.util.EnumUtil;
import org.jiuling.local.tools.verify.IntegerVerify;
import org.jiuling.local.tools.verify.ObjectVerify;
import org.jiuling.local.tools.verify.StringVerify;
import org.jiuling.weather.moji.enums.Base64WeatherIconEnums;
import org.jiuling.weather.moji.enums.WindDirEnum;
import org.jiuling.weather.moji.exception.MojiException;
import org.jiuling.weather.moji.model.AlertModel;
import org.jiuling.weather.moji.model.ForecastWeatherModel;
import org.jiuling.weather.moji.model.HourlyWeatherModel;

import java.util.ArrayList;
import java.util.List;

/**
 * 天气
 * @author 紫灵
 * @date 2022年09月14日 09时44分29秒
 */
public class MojiWeather {

    /**
     * 未来24小时
     * @param requestBody 请求数据
     * @return 小时天气模型列表
     */
    public List<HourlyWeatherModel> future24Hour(String requestBody) throws LocalToolsException, MojiException {
        String weather = analysisRequestBody(requestBody);
        JSONArray weatherJsonArray = JSON.parseObject(weather).getJSONArray("hourly");
        int weatherNum = weatherJsonArray.size();
        if(IntegerVerify.isBlank(weatherNum)){
            return null;
        }else {
            String path = this.getClass().getClassLoader().getResource("weatherIcon").getPath();
            List<HourlyWeatherModel> hourlyWeatherModelList = new ArrayList<>();
            for (int i=0;i<weatherNum;i++) {
                JSONObject jsonObject = weatherJsonArray.getJSONObject(i);
                HourlyWeatherModel hourlyWeatherModel = new HourlyWeatherModel();
                hourlyWeatherModel.setCondition(jsonObject.getString("condition"));
                hourlyWeatherModel.setConditionId(jsonObject.getString("conditionId"));
                hourlyWeatherModel.setDate(DateConvert.stringToDate(jsonObject.getString("date"), DateTimeFormatEnum.yyyy_MM_dd));
                hourlyWeatherModel.setHour(jsonObject.getString("hour"));
                hourlyWeatherModel.setHumidity(jsonObject.getString("humidity"));
                hourlyWeatherModel.setIce(jsonObject.getString("ice"));
                hourlyWeatherModel.setIconDay(getBase64Icon(path,jsonObject.getString("iconDay")));
                hourlyWeatherModel.setIconNight(getBase64Icon(path,jsonObject.getString("iconNight")));
                hourlyWeatherModel.setPop(jsonObject.getString("pop"));
                hourlyWeatherModel.setPressure(jsonObject.getString("pressure"));
                hourlyWeatherModel.setQpf(jsonObject.getString("qpf"));
                hourlyWeatherModel.setRealFeel(jsonObject.getString("realFeel"));
                hourlyWeatherModel.setSnow(jsonObject.getString("snow"));
                hourlyWeatherModel.setTemp(jsonObject.getString("temp"));
                hourlyWeatherModel.setUpdatetime(DateConvert.stringToDate(jsonObject.getString("updatetime"), DateTimeFormatEnum.yyyy_MM_dd_HH_mm_ss));
                hourlyWeatherModel.setUvi(jsonObject.getString("uvi"));
                hourlyWeatherModel.setWindDegrees(jsonObject.getString("windDegrees"));
                hourlyWeatherModel.setWindDir(EnumUtil.valueOfEnum(WindDirEnum.class,jsonObject.getString("windDir"),"getEnName").getName());
                hourlyWeatherModel.setWindSpeed(jsonObject.getString("windSpeed"));
                hourlyWeatherModel.setWindlevel(jsonObject.getString("windlevel"));
                hourlyWeatherModelList.add(hourlyWeatherModel);
            }
            return hourlyWeatherModelList;
        }
    }

    /**
     * 未来15天
     * @param requestBody 请求体数据
     * @return 预测天气模型列表
     */
    public List<ForecastWeatherModel> future15Day(String requestBody) throws MojiException, LocalToolsException {
        String weather = analysisRequestBody(requestBody);
        JSONArray weatherJsonArray = JSON.parseObject(weather).getJSONArray("forecast");
        int weatherNum = weatherJsonArray.size();
        if(IntegerVerify.isBlank(weatherNum)){
            return null;
        }else {
            String path = this.getClass().getClassLoader().getResource("weatherIcon").getPath();
            List<ForecastWeatherModel> forecastWeatherModelList = new ArrayList<>();
            for (int i=0;i<weatherNum;i++){
                JSONObject weatherJson = weatherJsonArray.getJSONObject(i);
                ForecastWeatherModel forecastWeatherModel = new ForecastWeatherModel();
                forecastWeatherModel.setConditionDay(weatherJson.getString("conditionDay"));
                forecastWeatherModel.setConditionIdDay(getBase64Icon(path,weatherJson.getString("conditionIdDay")));
                forecastWeatherModel.setConditionNight(weatherJson.getString("conditionNight"));
                forecastWeatherModel.setConditionIdNight(getBase64Icon(path,weatherJson.getString("conditionIdNight")));
                forecastWeatherModel.setHumidity(weatherJson.getString("humidity"));
                forecastWeatherModel.setMoonphase(weatherJson.getString("moonphase"));
                String moonrise = weatherJson.getString("moonrise");
                if(!StringVerify.isBlank(moonrise) && !"None".equals(moonrise)) {
                    forecastWeatherModel.setMoonrise(DateConvert.stringToDate(moonrise, DateTimeFormatEnum.yyyy_MM_dd_HH_mm_ss));
                }
                String moonset = weatherJson.getString("moonset");
                if(!StringVerify.isBlank(moonset) && !"None".equals(moonset)) {
                    forecastWeatherModel.setMoonset(DateConvert.stringToDate(moonset, DateTimeFormatEnum.yyyy_MM_dd_HH_mm_ss));
                }
                forecastWeatherModel.setPredictDate(DateConvert.stringToDate(weatherJson.getString("predictDate"),DateTimeFormatEnum.yyyy_MM_dd));
                forecastWeatherModel.setQpf(weatherJson.getString("qpf"));
                forecastWeatherModel.setSunrise(DateConvert.stringToDate(weatherJson.getString("sunrise"),DateTimeFormatEnum.yyyy_MM_dd_HH_mm_ss));
                forecastWeatherModel.setSunset(DateConvert.stringToDate(weatherJson.getString("sunset"),DateTimeFormatEnum.yyyy_MM_dd_HH_mm_ss));
                forecastWeatherModel.setTempDay(weatherJson.getIntValue("tempDay"));
                forecastWeatherModel.setTempNight(weatherJson.getIntValue("tempNight"));
                forecastWeatherModel.setUpdatetime(weatherJson.getString("updatetime"));
                forecastWeatherModel.setWindDegreesDay(weatherJson.getString("windDegreesDay"));
                forecastWeatherModel.setWindDegreesNight(weatherJson.getString("windDegreesNight"));
                forecastWeatherModel.setWindDirDay(weatherJson.getString("windDirDay"));
                forecastWeatherModel.setWindDirNight(weatherJson.getString("windDirNight"));
                forecastWeatherModel.setWindLevelDay(weatherJson.getString("windLevelDay"));
                forecastWeatherModel.setWindSpeedDay(weatherJson.getString("windSpeedDay"));
                forecastWeatherModel.setWindLevelNight(weatherJson.getString("windLevelNight"));
                forecastWeatherModel.setWindSpeedNight(weatherJson.getString("windSpeedNight"));
                forecastWeatherModel.setPop(weatherJson.getString("pop"));
                forecastWeatherModelList.add(forecastWeatherModel);
            }
            return forecastWeatherModelList;
        }
    }

    /**
     * 气象预警
     * @param requestBody 请求数据
     * @return 气象预警列表
     */
    public List<AlertModel> rainAlarmPro(String requestBody) throws MojiException, LocalToolsException {
        String rainAlarm = analysisRequestBody(requestBody);
        JSONArray rainAlarmJsonArray = JSON.parseObject(rainAlarm).getJSONArray("alert");
        if(ObjectVerify.isNull(rainAlarmJsonArray)){
            return null;
        }
        int alertNum = rainAlarmJsonArray.size();
        if(IntegerVerify.isBlank(alertNum)){
            return null;
        }else {
            List<AlertModel> alertModels = new ArrayList<>();
            for (int i=0;i<alertNum;i++){
                JSONObject rainAlarmJson = rainAlarmJsonArray.getJSONObject(i);
                AlertModel alertModel = new AlertModel();
                alertModel.setContent(rainAlarmJson.getString("content"));
                alertModel.setInfoid(rainAlarmJson.getLong("infoid"));
                alertModel.setLevel(rainAlarmJson.getString("level"));
                alertModel.setName(rainAlarmJson.getString("name"));
                alertModel.setPubTime(DateConvert.stringToDate(rainAlarmJson.getString("pub_time"),DateTimeFormatEnum.yyyy_MM_dd_HH_mm_ss));
                alertModel.setTitle(rainAlarmJson.getString("title"));
                alertModel.setUpdateTime(DateConvert.stringToDate(rainAlarmJson.getString("update_time"),DateTimeFormatEnum.yyyy_MM_dd_HH_mm_ss));
                alertModel.setType(rainAlarmJson.getString("type"));
                alertModels.add(alertModel);
            }
            return alertModels;
        }
    }

    /**
     * 获取base64位图标
     * @param path 路径
     * @param id 图标id
     * @return base65位图标
     */
    private String getBase64Icon(String path,String id) throws LocalToolsException {
        return EnumUtil.valueOfEnum(Base64WeatherIconEnums.class,Integer.valueOf(id),"getId").getIconBase64();
    }

    /**
     * 解析请求体数据
     * @param requestBody 请求体
     * @return data书
     */
    private String analysisRequestBody(String requestBody) throws MojiException {
        JSONObject jsonObject = JSON.parseObject(requestBody);
        if(jsonObject.getInteger("code").equals(0)){
            return jsonObject.getString("data");
        }else {
            throw new MojiException(jsonObject.getString("msg"));
        }
    }

}
